<?php
/**
 * Created by 784855684@qq.com.
 * Link: https://github.com/lichtung/wshore
 * User: linzh
 * Date: 7/11/17
 * Time: 9:06 AM
 */
declare(strict_types=1);


namespace application\module\admin\controller;


use application\module\admin\model\NotificationModel;
use wshore\core\Response;
use wshore\helper\Network;
use wshore\throws\db\RecordNotFoundException;

class notification extends admin
{
    private $httpServer;
    /**
     * @param int $nid 消息ID
     * URL:/admin/notification/setnotificactionlooked
     */
    public function setNotificactionLooked(int $nid)
    {
        try {
            $model = new NotificationModel($nid);
            if ($model->receiver and $model->receiver === self::$user->email) {
                $model->looked = WS_NOW;
                $model->save() ?
                    Response::success('标记已经读取成功') :
                    Response::failure('标记已经读取失败:' . $model->error());
            }
            Response::failure('消息标记错误');
        } catch (RecordNotFoundException $exception) {
            Response::failure('消息不存在');
        }
    }

    /**
     * 消息内容
     *
     * 地址:/admin/notification/push
     *
     * @param int $uid
     * @param string $receiver
     * @param string $content
     * @return void
     */
    public function push(int $uid = 0, string $receiver = '', string $content='')
    {
        $ar = new NotificationModel();
        $ar->sender = self::$user->email;
        if ($uid) {
            $ar->receiver = md5(SECRET_KEY . $uid);
        } else {
            $ar->receiver = $receiver;
        }
        $ar->looked = 0;
        $ar->title = '';
        $ar->content = $content;
        if ($ar->save(true)) {
            $data = $_GET;
            $data['function'] = 'transmit';
            $data['from'] = $ar->sender;
            $data['to'] = $ar->receiver;
            $data['content'] = $ar->content;

            $res = Network::getJson($this->httpServer . '?' . http_build_query($data));

            if ((int)($res['status']??0) < 1) {
                Response::failure("接收者'$receiver'不在线,消息将再上线后推送");
            } else {
                Response::success('推送成功');
            }
        } else {
            Response::success('存储过程中出现错误:' . $ar->error() . $ar->getLastSql());
        }
    }

    /**
     *
     * URL:admin/notification/getunlookednotificationlist
     */
    public function getUnlookedNotificationList()
    {
        $ar = new NotificationModel(self::$user->email);
        $list = $ar->getUnlookedNotificationList();
        Response::success('获取成功', $list);
    }
}